# encoding: utf-8
# 项目名称： day02
# @File  : auth.py
# @Author: sun hao
# @Desc : 中间件 auth.py
# @Date  :   16:30 2024/10/05
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect


class M1(MiddlewareMixin):
    """
    中间件1
    """

    def process_request(self, request):
        print("M1,进来了")
        # 如果没有返回值，或者 返回None 它可以继续走下去
        # 如果有返回值，直接 HttpResponse，后面就不执行了
        return HttpResponse("无权访问")

    def process_response(self, request, responses):
        print("M1,走了")
        return responses


class M2(MiddlewareMixin):
    """
    中间件2
    """

    def process_request(self, request):
        print("M2,进来了")

    def process_response(self, request, responses):
        print("M2,走了")
        return responses


class CheckAuthMiddleware(MiddlewareMixin):
    """
        检查当前访问用户的session信息
    """

    def process_request(self, request):
        # 排除 登录页面 login，它不需要用户session可以直接访问
        if request.path_info in ["/login/","/image/code/","/upload/list/"]:
            return
        # 1、尝试读取访问用户的session信息，如果有 下一步 如果没有 请先去登录
        login_info = request.session.get("login_info")
        if login_info:
            return

        return redirect("/login/")
        # if not login_info:
        #     # 没有session信息，去登录
        #     # return HttpResponse("请先登录")
        #     return redirect("/login/")
        # # 有 session信息 下一步
        # return
    def process_response(self, request, response):
        # 添加防止缓存的HTTP头
        response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        response['Pragma'] = 'no-cache'
        response['Expires'] = '0'
        return response
